﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Schema;

namespace dasBlog.Storage
{
    public static class StorageNodeClient 
    {
        public static XmlSchema GetItemSchema(this IStorageNode node, string baseUri, string schemaId)
        {
            var result = node.GetItemSchema(baseUri, schemaId);
            if (result != null)
            {
                XmlSchema schema = XmlSchema.Read(result.GetReaderAtBodyContents(), null);
                result.Close();
                return schema;
            }
            return null;
        }

        public static IList<T> Select<T>(this IStorageNode node, Moniker moniker, MonikerMatch match, QueryDescription query) where T : class, new()
        {
            return SerializationTools<T>.DeserializeList(
                node.Select(null, moniker, match, query, SerializationMode.Native)
                );
        }

        public static IList<PropertyAggregate> Aggregate(this IStorageNode node, Moniker moniker, MonikerMatch match, string propertyName)
        {
            return SerializationTools<PropertyAggregate>.DeserializeList(
                node.Aggregate(null, moniker, match, propertyName, SerializationMode.Native)
                );
        }

        public static T Get<T>(this IStorageNode node, Moniker itemId) where T : class, new()
        {
            return SerializationTools<T>.Deserialize(
                node.Get(null,itemId,SerializationMode.Native)
                );
        }

        public static void Delete(this IStorageNode node, Moniker itemId)
        {
            node.Delete(itemId);
        }

        public static Moniker Store<T>(this IStorageNode node, Moniker moniker, T item) where T : class, new()
        {
            return node.Store(moniker, SerializationTools<T>.ToXmlElement(item), SerializationMode.Native);
        }
    }
}
